﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using MedicalSystem.SamrtReport.Library;
using System.Diagnostics;

namespace MedicalSystem.SamrtReport
{
    public partial class DataBindingSettingFrm : Form
    {
        public DataBindingSettingFrm(Control control,bool isMobile)
        {
            InitializeComponent();
            this._selectedControl = control;
            this._isMobile = isMobile;
        }

        private Control _selectedControl;
        private bool _isMobile;
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.listBox1.SelectedItem != null)
                SetControlDataBinding(this.listBox1.SelectedItem as ListBoxItem);
            this.DialogResult = DialogResult.OK;
        }

        private void SetControlDataBinding(ListBoxItem selectItem)
        {
          
            _selectedControl.DataBindings.Clear();
           
          
            if (this._selectedControl is TextBox || this._selectedControl is RichTextBox || this._selectedControl is Label)
            {
                _selectedControl.DataBindings.Add(new Binding("Text", dataSource, this.comboBox1.Text + "." + selectItem.Value));
            }
            else if (this._selectedControl is ComboBox || this._selectedControl is ListBox)
            {
                _selectedControl.DataBindings.Add(new Binding("SelectedValue", dataSource, this.comboBox1.Text + "." + selectItem.Value));
            }
            else if (this._selectedControl is NumericUpDown || this._selectedControl is DateTimePicker)
            {
                _selectedControl.DataBindings.Add(new Binding("Value", dataSource, this.comboBox1.Text + "." + selectItem.Value));
            }
            else if (this._selectedControl is CheckBox || this._selectedControl is RadioButton)
            {
                _selectedControl.DataBindings.Add(new Binding("Checked", dataSource, this.comboBox1.Text + "." + selectItem.Value));
            }
            else if (this._selectedControl is UserControl )
            {
                if (_isMobile)
                {
                    MemberInfo[] memberInfo = this._selectedControl.GetType().GetDefaultMembers();
                    if (memberInfo.Length > 0)
                    {
                        _selectedControl.DataBindings.Add(new Binding(memberInfo[0].Name, dataSource, this.comboBox1.Text + "." + selectItem.Value));
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("不能添加绑定项,未找到Mobile自定义控件'{0}'的默认数据绑定属性", _selectedControl.Name));
                    }
                }
                else
                {
                    object[] defaultBinding = this._selectedControl.GetType().GetCustomAttributes(typeof(DefaultBindingPropertyAttribute), false);
                    if (defaultBinding.Length > 0)
                    {
                        string propertyName = ((DefaultBindingPropertyAttribute)defaultBinding[0]).Name;
                        _selectedControl.DataBindings.Add(new Binding(propertyName, dataSource, this.comboBox1.Text + "." + selectItem.Value));
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("不能添加绑定项,未找到Windows自定义控件'{0}'的默认数据绑定属性", _selectedControl.Name));
                    }
                }
               
               
            }
        }
        private void FDataBindingSetting_Load(object sender, EventArgs e)
        {
            Initalize();
            CustomFormHepler.ShowForm(this);
        }
        private DataSet dataSource = new DataSet();
        private void Initalize()
        {
            string[] files = Directory.GetFiles(BindingData.Path);
            if (files.Length == 0)
            {
                Trace.WriteLine("提示,您当前设计器中无可用数据源,请通过数据源添加向导添加数据源到表单设计器!");
            }
            else
            {
                this.BindingNameComboBox.Items.Clear();

                foreach (string file in files)
                {
                    if (Path.GetExtension(file).ToLower() != ".xml")
                        continue;
                    string fileName = Path.GetFileNameWithoutExtension(file);
                    this.BindingNameComboBox.Items.Add(fileName);
                }

                if (BindingNameComboBox.Items.Count == 0)
                    Trace.WriteLine("提示,您当前设计器中无可用数据源,请通过数据源添加向导添加数据源到表单设计器!");

                if (string.IsNullOrEmpty(BindingData.CurrentBindingSourceName))
                {
                    Trace.WriteLine("提示,请设置当前表单的绑定数据源!");
                    this.BindingNameComboBox.Enabled = true;
                    this.BindingNameComboBox.SelectedIndexChanged+=new EventHandler(BindingNameComboBox_SelectedIndexChanged);
                }
                else
                {
                    if (BindingNameComboBox.Items.Contains(BindingData.CurrentBindingSourceName))
                        BindingNameComboBox.Text = BindingData.CurrentBindingSourceName;
                    else
                    {
                        Trace.WriteLine(
                            string.Format("提示,设计器中不存在您当前打开表单的数据源<{0}>,你可以选择其它类型匹配的数据源作为绑定数据源，还可以使用绑定数据源配置向导，添加新数据源!",
                            BindingData.CurrentBindingSourceName),"Error");
                        this.BindingNameComboBox.Enabled = true;
                        this.BindingNameComboBox.SelectedIndexChanged += new EventHandler(BindingNameComboBox_SelectedIndexChanged);
                    }
                }

                if (!string.IsNullOrEmpty(BindingNameComboBox.Text))
                {
                    LoadDataMember();
                }

            }
            if (this._selectedControl.DataBindings.Count > 0)
            {
                string bindingMember = this._selectedControl.DataBindings[0].BindingMemberInfo.BindingMember;
                string[] data = bindingMember.Split(new char[] { '.' });
                this.comboBox1.Text = data[0];
                comboBox1_SelectedIndexChanged(comboBox1, EventArgs.Empty);
                this.listBox1.SelectedIndex = dataSource.Tables[comboBox1.Text].Columns[data[1]].Ordinal;
            }
            else
            {
                if(this.comboBox1.Items.Count>0)
                     this.comboBox1.SelectedIndex = 0;
            }
        }
        private void LoadDataMember()
        {
            if (File.Exists(string.Format(@"{0}\{1}.xml", BindingData.Path, BindingNameComboBox.Text)))
            {
                this.comboBox1.Items.Clear();
                dataSource.ReadXmlSchema(string.Format(@"{0}\{1}.xml", BindingData.Path, BindingNameComboBox.Text));

                for (int i = 0; i < dataSource.Tables.Count; i++)
                {
                    this.comboBox1.Items.Add(dataSource.Tables[i].TableName);

                }
            }
            else
            {
                Trace.WriteLine(string.Format("找不到名为<{0}>的数据源!", BindingNameComboBox.Text));
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(comboBox1.Text))
                return;
            this.listBox1.Items.Clear();
            for (int j = 0; j < dataSource.Tables[comboBox1.Text].Columns.Count; j++)
            {
                ListBoxItem item = new ListBoxItem();
                item.Text = dataSource.Tables[comboBox1.Text].Columns[j].Caption;
                item.Value = dataSource.Tables[comboBox1.Text].Columns[j].ColumnName;
                this.listBox1.Items.Add(item);
            }
            this.button1.Enabled = false;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.button1.Enabled = listBox1.SelectedItem != null;

        }

        private void BindingNameComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(BindingNameComboBox.Text))
            {
                if (MessageBox.Show(string.Format("是否确定选择<{0}>作为当前表单的绑定数据源", BindingNameComboBox.Text), 
                    "提示框", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    LoadDataMember();
                    BindingNameComboBox.Enabled = false;
                    BindingData.CurrentBindingSourceName = BindingNameComboBox.Text;
                }
               

            }
        }

      
    }
}
